package com.wan.net.handler;

import com.wan.net.core.packet.Packet;
import com.wan.net.handler.protobuf.Processor;
import com.wan.net.session.AttributeKeys;
import com.wan.thread.actor.Actor;
import com.wan.thread.actor.ActorExecutor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

public class ProtobufServerChannelHandler extends AbstractServerChannelHandler {

    private static final ActorExecutor executor;
    static {
        executor = new ActorExecutor(Runtime.getRuntime().availableProcessors() * 2,"msg-handler");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Packet packet) throws Exception {
        Processor handler = Processor.getServerProcessor(packet.getMessageId());
        if(handler == null){
            logger.error("找不到协议号[{}]对应的处理器",packet.getMessageId());
            return;
        }
        Channel channel = channelHandlerContext.channel();
        //放到指定线程上执行
        executor.execute(new Actor() {
            @Override
            public long asyncId() {
                //绑定id
                return AttributeKeys.get(channel,AttributeKeys.CHANNEL_ID);
            }

            @Override
            public void run() {
                try {
                    handler.process(channel, packet);
                }catch (Exception e){
                    logger.error("协议[{}]处理异常",packet.getMessageId(),e);
                }
            }
        });
    }
}
